package br.furb.model;

import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.AbstractCellEditor;
import javax.swing.JButton;
import javax.swing.JTable;
import javax.swing.UIManager;
import javax.swing.table.TableCellEditor;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumnModel;

import br.furb.util.Imagem;

public class ButtonColumn extends AbstractCellEditor implements TableCellEditor, TableCellRenderer, ActionListener {

	/**
	 * 
	 */
	private static final long serialVersionUID = 8448530836833963658L;
	
	private JTable table;
	private JButton renderButton;
	private JButton editButton;
	
	public ButtonColumn(JTable table, int column) {
		super();
		this.table = table;
		
		renderButton = new JButton();
		renderButton.setIcon(Imagem.icone("delete.png"));
		renderButton.setBorderPainted(false);
		renderButton.setContentAreaFilled(false);
		
		editButton = new JButton();
		editButton.setIcon(Imagem.icone("delete.png"));
		editButton.setBorderPainted(false);
		editButton.setContentAreaFilled(false);
		editButton.setFocusPainted(false);
		editButton.addActionListener(this);
		
		TableColumnModel columnModel = table.getColumnModel();
		columnModel.getColumn(column).setCellRenderer(this);
		columnModel.getColumn(column).setCellEditor(this);
	}
	
	@Override
	public Object getCellEditorValue() {
		return "";
	}

	@Override
	public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
		if (hasFocus) {
			renderButton.setForeground(table.getForeground());
			renderButton.setBackground(UIManager.getColor("Button.background"));
		} else if (isSelected) {
			renderButton.setForeground(table.getSelectionForeground());
			renderButton.setBackground(table.getSelectionBackground());
		} else {
			renderButton.setForeground(table.getForeground());
			renderButton.setBackground(UIManager.getColor("Button.background"));
		}
		return renderButton;
	}

	@Override
	public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
		return editButton;
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		fireEditingStopped();
		TableModel<?> tm = (TableModel<?>) this.table.getModel();
		tm.removeItem(this.table.getSelectedRow());
	}
}